package com.work.user.controller;

import com.work.entity.Result;
import com.work.entity.StatusCode;
import com.work.user.pojo.Role;
import com.work.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/findAll")
    public Result findAll(){
        try {
            List<Role> roleList = roleService.findAll();
            return new Result(true,StatusCode.FIND_Ok,"查询成功",roleList);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, StatusCode.FIND_ERROR,"查询失败");
        }
    }

    //根据id查询角色
    @GetMapping("/findById")
    public Result findById(@RequestParam Integer id){
        try {
            Role role = roleService.findById(id);
            return new Result(true,StatusCode.FIND_Ok,"查询成功",role);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, StatusCode.FIND_ERROR,"查询失败");
        }
    }

    @PostMapping("/add")
    public Result add(@RequestBody Role role,@RequestParam Integer[] mids){
        try {
            roleService.add(role,mids);
            return new Result(true,StatusCode.ADD_OK,"添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.ADD_ERROR,"添加失败");
        }
    }

    @PutMapping("/update")
    public Result update(@RequestBody Role role,@RequestParam Integer[] mids){
        try {
            roleService.update(role,mids);
            return new Result(true,StatusCode.UPDATE_Ok,"修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.UPDATE_ERROR,"修改失败");
        }
    }

    @DeleteMapping("/delete")
    public Result delete(@RequestParam Integer id){
        try {
            if (id==1){
                return new Result(false,StatusCode.DELETE_ERROR,"超级管理员不允许删除");
            }
            roleService.delete(id);
            return new Result(true,StatusCode.DELETE_OK,"删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.DELETE_ERROR,"删除失败");
        }
    }

}
